package com.sneakxy.mybatis.commons.repository.query.executor;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.binding.MapperMethod.ParamMap;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.scripting.xmltags.MixedSqlNode;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.scripting.xmltags.TextSqlNode;
import org.apache.ibatis.scripting.xmltags.WhereSqlNode;

import com.sneakxy.mybatis.commons.orm.MybatisEntityManager;
import com.sneakxy.mybatis.commons.repository.query.domain.Criteria;
import com.sneakxy.mybatis.commons.repository.query.domain.CriteriaSqlNode;
import com.sneakxy.mybatis.commons.repository.query.parser.MybatisPartTree;

/**
 * @author 潜行的青衣
 */
public class CriteriaDeleteRepositoryExecutor extends AbstractRepositoryExecutor<Long> {

	/**
	 * @param entityManager
	 * @param loader
	 * @param method
	 * @param type
	 */
	public CriteriaDeleteRepositoryExecutor(MybatisEntityManager entityManager, Class<?> loader, String method,
			Class<?>... type) {
		super(entityManager, loader, method, type);
	}

	/**
	 * @param entityManager
	 * @param method
	 */
	public CriteriaDeleteRepositoryExecutor(MybatisEntityManager entityManager, Method method) {
		super(entityManager, method);
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybatis.commons.repository.query.executor.RepositoryExecutor#execute(java.lang.Object[])
	 */
	@Override
	public Long execute(Object... parameters) {
		Object parameterObject = this.createParameterObject(parameters, false);
		return Long.valueOf(this.getEntityManager().getSqlSessionTemplate().delete(getStatement(), parameterObject));
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybatis.commons.repository.query.executor.AbstractRepositoryExecutor#onBuildStatment()
	 */
	@Override
	protected void onBuildStatment() {
		StringBuilder sqlBuilder = new StringBuilder();
		List<SqlNode> contents = new ArrayList<>();
		WhereSqlNode whereSqlNode = new WhereSqlNode(this.getEntityManager().getConfiguration(), new CriteriaSqlNode(this.getEntityManager().getConfiguration(), getCriteriaIndex()));
		sqlBuilder.append("DELETE FROM ${").append(MybatisPartTree.GENERIC_NAME_PREFIX).append("2} ");
		contents.add(new TextSqlNode(sqlBuilder.toString()));
		contents.add(whereSqlNode);
		String id = this.getStatement();
		SqlCommandType sqlCommandType  = SqlCommandType.DELETE;
		SqlSource sqlSource = new DynamicSqlSource(this.getEntityManager().getConfiguration(), new MixedSqlNode(contents));
		this.getEntityManager().addMappedStatement(id, sqlSource, sqlCommandType, ParamMap.class, Long.class);
	}

	public int getCriteriaIndex() {
		int index = 1;
		for(Class<?> type:this.getMethod().getParameterTypes()) {
			if(Criteria.class.isAssignableFrom(type)) {
				break;
			}
			index ++;
		}
		return index;
	}
	
}
